package com.hnhs.controller;

import cn.hutool.core.io.FileUtil;


import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import com.hnhs.model.CsvData;
import com.hnhs.model.Popular;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;


public class CsvController {

    //@PostMapping("/upload")
    public String uploadCsv(@RequestParam("file") MultipartFile file) {
        try {
            File csvFile = new File(System.getProperty("java.io.tmpdir"), file.getOriginalFilename());
            file.transferTo(csvFile);
            List<CsvData> dataList = readAndProcessCsvFile(csvFile);
            // 这里可以添加代码将dataList保存到数据库
            return "CSV文件上传并处理成功: " + dataList.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "CSV文件上传或处理失败";
        }
    }

    private List<CsvData> readAndProcessCsvFile(File csvFile) throws Exception {
        Reader reader = FileUtil.getReader(csvFile, "UTF-8");
        CsvReader csvReader = CsvUtil.getReader(reader);
        List<CsvData> dataList = new ArrayList<>();
        cn.hutool.core.text.csv.CsvData rows = csvReader.read();

//        for (List<Object> row : rows) {
//            Popular data = new Popular();
//            if (row.size() > 0) data.setColumn1((String) row.get(0));
//            if (row.size() > 1) {
//                String priceRange = (String) row.get(1);
//                String[] prices = priceRange.split("-", 2); // Split into two parts
//                if (prices.length > 0) data.setMinprice(prices[0].trim());
//                if (prices.length > 1) data.setMaxprice(prices[1].trim());
//            }
//            dataList.add(data);
        //}
        csvReader.close();
        return dataList;
    }
}
